package com.pkk.penguin.frame.know.shiro.shirodemo.springversion.controller;

import com.pkk.components.rpc.response.CommonResponse;
import com.pkk.components.rpc.response.util.ResponseUtil;
import com.pkk.penguin.frame.know.shiro.shirodemo.springversion.entity.TbUserEntity;
import com.pkk.penguin.frame.know.shiro.shirodemo.springversion.service.TbUserService;
import com.pkk.penguin.frame.know.shiro.shirodemo.springversion.vo.request.UserLogReqData;
import com.pkk.penguin.frame.know.shiro.shirodemo.util.enums.ShiroCode;
import java.io.IOException;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * @description: 用户访问控制器
 * @author: peikunkun
 * @create: 2018-08-22 10:23
 **/
@RequestMapping("user")
@RestController
@Slf4j
public class UserController extends BaseController {

  @Resource
  private TbUserService tbUserService;


  /**
   * 用户登录
   *
   * @param user
   */
  @RequestMapping(value = "/login", method = {RequestMethod.POST, RequestMethod.GET})
  public CommonResponse<Boolean> login(@RequestBody UserLogReqData user) throws IOException {

    //用户登录
    TbUserEntity userInfo = tbUserService.selectUserInfoByName(user.getUserName());
    if (userInfo == null) {
      return ResponseUtil.error(ShiroCode.LOGIN_FAIL);
    }
    if (!userInfo.getPwd().equals(new Sha256Hash(user.getPassword()).toHex())) {
      return ResponseUtil.error(ShiroCode.PWD_ERROR);
    }
    //存入session
    Subject subject = SecurityUtils.getSubject();
    //记得传入明文密码
    subject.login(new UsernamePasswordToken(user.getUserName(), user.getPassword(), user.getRememberMe()));
    session.setAttribute(USER_SESSION, userInfo);
    return ResponseUtil.success();
  }


  /**
   * 用户登录
   *
   * @param user
   */
  @RequestMapping(value = "/logout", method = {RequestMethod.POST, RequestMethod.GET})
  public CommonResponse<Boolean> logout(@RequestBody UserLogReqData user) throws IOException {

    //用户登录
    TbUserEntity userInfo = tbUserService.selectUserInfoByName(user.getUserName());
    if (userInfo == null) {
      return ResponseUtil.error(ShiroCode.LOGIN_FAIL);
    }
    if (!userInfo.getPwd().equals(new Sha256Hash(user.getPassword()).toHex())) {
      return ResponseUtil.error(ShiroCode.PWD_ERROR);
    }
    //存入session
    Subject subject = SecurityUtils.getSubject();
    subject.logout();
    return ResponseUtil.success();
  }


}
